package threading;

import java.util.concurrent.PriorityBlockingQueue;

class MyTaskCyh implements Comparable<MyTaskCyh>{
    //
    // 要做啥？
    public Runnable runnable;
    // 时间是多少？
    public long time;


    public MyTaskCyh(Runnable runnable, long delay){
        this.runnable = runnable;
        //  取当前时刻的时间戳 加上 delay ，作为该任务实际执行的时间戳
        this.time = System.currentTimeMillis() + delay;
    }

    // 比较规则，实现优先级

    @Override
    public int compareTo(MyTaskCyh o) {
        //  这样表示每次取出的是时间最小的元素
        return (int)(this.time - o.time);
    }
}

class MyTimerCyh{
    // 带优先级的阻塞队列  定时器最关键的部分

    //  <>尖括号里的元素要封装起来，所以写了一个MyTask类
    private PriorityBlockingQueue<MyTaskCyh> queue = new PriorityBlockingQueue<>();

    // 创建一个锁对象
    public Object locker = new Object();
    // schedule方法
    public void schedule(Runnable runnable,long delay){
        //  根据参数，构造MyTask，插入队列
        MyTaskCyh myTask = new MyTaskCyh(runnable,delay);
        queue.put(myTask);
        synchronized (locker) {
            locker.notify();
        }
    }

    // 在这里构造线程，负责执行具体的任务
    public MyTimerCyh(){
        Thread thread = new Thread( () -> {
            while (true){
                try {
                    synchronized (locker) {
                        MyTaskCyh myTask = queue.take();
                        long currentTime = System.currentTimeMillis();
                        if(currentTime >= myTask.time){
                            //  时间到了，可以执行任务
                            myTask.runnable.run();
                        }else{
                            //  时间还没到
                            //  把刚才取出的任务，重新塞回到队列里
                            queue.put(myTask);
                            locker.wait(myTask.time - currentTime);
                        }
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        } );
        thread.start();
    }
}

public class ThreadDemo11 {
    public static void main(String[] args) {
        MyTimerCyh myTimer = new MyTimerCyh();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello4");
            }
        },4000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello3");
            }
        },3000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello2");
            }
        },2000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello1");
            }
        },1000);

        System.out.println("hello 0");
    }
}
